<?php

declare(strict_types=1);

namespace App\Admin\Actions\User;

use App\Constant\CacheKey;
use App\Library\RedisClient;
use App\Library\SnowFlakeId;
use App\Models\Admin\User\User;
use App\Models\User\User\UserScoreHistory;
use Encore\Admin\Actions\RowAction;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Throwable;

class UserScoreAction extends RowAction
{
    public $name = "积分操作";

    public function handle(Model $model, Request $request)
    {
        $requestParams = $request->all();
        DB::beginTransaction();
        try {
            if ($requestParams["type"] == 1) {
                $updateRow = User::query()->where("uid", "=", $requestParams["uid"])->increment("score", $request["score"]);
                $cacheRow = RedisClient::client()->incrByFloat(CacheKey::$scoreKey . $requestParams["uid"], (float)$requestParams["score"]);
                $score = UserScoreHistory::query()->create([
                    "uid" => SnowFlakeId::getId(),
                    "title" => "平台增加",
                    "user_uid" => $requestParams["uid"],
                    "score" => $requestParams["score"],
                    "type" => 1,
                ])->getKey();
            } else {
                $updateRow = User::query()->where("uid", "=", $requestParams["uid"])->decrement("score", $request["score"]);
                $cacheRow = RedisClient::client()->incrByFloat(CacheKey::$scoreKey . $requestParams["uid"], -(float)$requestParams["score"]);
                $score = UserScoreHistory::query()->create([
                    "uid" => SnowFlakeId::getId(),
                    "title" => "平台减少",
                    "user_uid" => $requestParams["uid"],
                    "score" => $requestParams["score"],
                    "type" => 2,
                ])->getKey();
            }
            if ($updateRow && $cacheRow && $score) {
                DB::commit();
                return $this->response()->success("积分操作成功")->refresh();
            }
            DB::rollBack();
            return $this->response()->error("积分操作失败");
        } catch (Throwable $throwable) {
            DB::rollBack();
            return $this->response()->error("积分操作失败");
        }
    }

    public function form()
    {
        $uid = $this->getRow()->getAttribute("uid");
        $this->hidden("uid", "数据id")->default($uid);
        $this->text("score", "积积分值")->rules("required|regex:/^\d*(\.\d{1,2})?$/")->help("最多两位小数");
        $this->radio("type", "操作类型")->options([1 => "增加", 2 => "减少"])->required();
    }
}
